import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.List;

import javax.swing.JOptionPane;
import javax.swing.SwingWorker;


public class Sender extends SwingWorker<Void, Integer>
{
	File f;
	static Socket server;
	public Sender(File f) 
	{ 
		this.f=f; 
	}
	public void Send(File f) throws UnknownHostException, IOException, InterruptedException
	{
		 server = new Socket("localhost", 7777);
		 System.out.print(f.getName());
		 DataOutputStream outD = new DataOutputStream(server.getOutputStream());
		 outD.writeLong(f.length());
		 outD.writeUTF(f.getName());
		 FileInputStream in = new FileInputStream(f);
         byte[] buffer = new byte[64*1024];
         int count,total = 0;
         while((count = in.read(buffer)) != -1)
         {
        	 total += count;
        	 
             outD.write(buffer, 0, count);
             Integer n = (int) ((total*100)/f.length());
             publish(n);
         }
         outD.flush();
         in.close();
         server.close();
         JOptionPane.showMessageDialog(Main.frame, "Файл успешно отправлен","Информация",JOptionPane.INFORMATION_MESSAGE);
	}
	@Override
	protected Void doInBackground() throws Exception 
	{
		Send(f);
		return null;
	}
	@Override
    protected void process(List<Integer> chunks) 
	{
        for (int number : chunks) 
        {
        	Main.progressBar.setValue(number);
        }
    }

}
